package com.annet.token.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.annet.token.utils.AESUtils;
import com.annet.token.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;

/**
 * Copyright © 2016 深圳安泰创新科技股份有限公司 版权所有 All Right Reserved
 *
 * @author: chenkaidong
 * 包名：com.annet.token.service
 * 时间：2021/1/19
 */
@Slf4j
@Service
public class SecurityParamServiceImpl {

    @Value("${annet.rsa.privateKey}")
    private String rsaPrivateKey;


    @Value("${annet.rsa.publicKey}")
    private String rsaPublicKey;

    private final String encode = "UTF-8";

    public String decrypt(JSONObject json) throws Exception {
        String encryptKey = json.getString("encryptKey");
        String encryptData = json.getString("encryptData");

        if (StrUtil.isBlank(encryptKey)) {
            throw new Exception("加密密钥为空，请检查参数");
        }

        // RSA私钥解密AES秘钥key（keyEn）
        String AesKey = null;
        try {
            AesKey = RSAUtils.decrypt(encryptKey, rsaPrivateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // AES秘钥key解密数据
        return StrUtil.isNotBlank(encryptData) ? AESUtils.decrypt(AesKey, encryptData, encode) : "";

    }

    public JSONObject encrypt(JSONObject jsonData) throws Exception {
        // 自动生成ASE密钥
        KeyGenerator keyGen = null;
        try {
            keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(128);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SecretKey key = keyGen.generateKey();
        String AESKeyStr = Base64.encodeBase64String(key.getEncoded());
        log.info("随机生成的AES加密秘钥（AESKeyStr）为：" + AESKeyStr);

        // 加密数据
        String encryptData = AESUtils.encrypt(AESKeyStr, jsonData.toJSONString(), encode);
        // RSA加密后的AES密钥
        String encryptKey = RSAUtils.encrypt(AESKeyStr, rsaPublicKey);

        JSONObject result = new JSONObject();
        result.put("encryptKey", encryptKey);
        result.put("encryptData", encryptData);
        result.put("aesKey", AESKeyStr);
        return result;
    }
}
